package com.gollum.jpa.factory;

import com.gollum.jpa.dao.impl.JpaDaoImpl;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 *  将自己封装的jpaDao 丢该工厂去做生产
 *
 * @author Herther
 * @version 1.0.0
 * @date: 2022/8/6 23:29
 */
public class JpaDaoFactoryBean<R extends JpaRepository<T, I>, T,
        I extends java.io.Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    public JpaDaoFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new JpaDaoFactory(em);
    }

    /**
     * 创建一个内部类，该类不用在外部访问
     *
     * @param <T>
     * @param <I>
     */
    private static class JpaDaoFactory<T, I extends java.io.Serializable>
            extends JpaRepositoryFactory {

        private final EntityManager em;

        public JpaDaoFactory(EntityManager em) {
            super(em);
            this.em = em;
        }

        /**
         * 设置具体的实现类是JpaDaoFactory
         *
         * @param information
         * @return
         */
        @Override
        protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information,
                                                                        EntityManager entityManager) {
            return new JpaDaoImpl((Class<T>) information.getDomainType(), entityManager);
        }

        /**
         * 获取具体的实现类的class
         *
         * @param metadata
         * @return
         */
        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return JpaDaoImpl.class;
        }

    }



}
